/**
 * Created by huangzx on 2015/6/24.
 */
define('framework/dict/GillionDictModule', [
    'angular',
    'config.properties'
], function (angular, config) {
    return angular.module('GillionDictModule', [], ['$filterProvider', '$compileProvider', function ($filterProvider, $compileProvider) {
        var dictConfig = config.dict_config || {},
            gDictValue = angular.element('body').attr('g-dict'),
            filterFn = angular.noop,
            requested = false,
            dictData,     //ajax返回的数据字典数据
            filterNames,  //过滤器数组名称
            params,
            i,len;

        //http请求调用初始化
        function requestFn($http, $rootScope) {
            if (!dictData && requested === false) {
                requested = true;
                $http({
                    method:dictConfig.method||'get',
                    url:dictConfig.url+"?"+params,
                    data:dictConfig.data || ''
                }).then(function (result) {
                    var $dict = $rootScope.$dict || {};
                    dictData = result.data;
                    //返回的数据放入到$rootScope属性中，以便后续的获取
                    angular.forEach(dictData, function(dictObj, dictKey){
                        $dict[dictKey] = [];
                        angular.forEach(dictObj, function(value, key){
                            $dict[dictKey].push({key:key, value:value});
                        });
                    });
                    $rootScope.$dict = $dict;

                    filterFn = function (filterName, input, reverse) {
                        var data, key;
                        if(dictData) data = dictData[filterName];
                        if (!data) return input;
                        reverse = !!reverse;
                        if (!reverse) return data[input];
                        for (key in data) {
                            if (data[key] == input) return key;
                        }
                        return input;
                    }
                });
            }
        }

        if (!gDictValue) return;
        filterNames = gDictValue.split(',');
        len = filterNames.length;
        params = 'params='+gDictValue;
        if(dictConfig.params) params = params+"&"+dictConfig.params;

        $compileProvider.directive('gDict', ['$http', '$rootScope', function($http, $rootScope){
            requestFn($http, $rootScope);
            return {
                restrict: 'A'
            };
        }]);

        //定义多个过滤器
        for (i=0;i<len;i++){
            (function (filerName) {
                $filterProvider.register(filerName, ['$http', '$rootScope',function($http, $rootScope){
                    requestFn($http, $rootScope);
                    return function(input, reverse) {
                        return filterFn(filerName, input, reverse);
                    }
                }]);
            })(filterNames[i]);
        }

    }]);
});